import React, { Component } from "react";
import { Modal, Input, TreeSelect, Form, Spin, message } from "antd";
import { connect } from "dva";
import SelectModal from "../../recommendCenter/add/components/SelectModal";

const { TextArea } = Input;

@connect(stores => ({
  userData: stores.user,
  orgList: stores.adddataSource,
  appData: stores.appListData
}))
@Form.create()
class AddApplication extends Component {
  state = {
    managerName: "",
    manager: "",
    ownerDept: "",
    ownerDeptName: "",
    selectVisible: false,
    loadingEdit: false
  };

  componentDidUpdate(prevProps) {
    const { visible } = this.props;
    if (prevProps.visible !== visible && visible === true) {
      this.init();
    }
  }

  init = async () => {
    this.setLoading(true);
    const {
      dispatch,
      appId,
      form: { setFieldsValue },
      userData: {
        userInfo: {
          userId = "",
          userName = "",
          department = "",
          departmentName = ""
        }
      }
    } = this.props;
    dispatch({ type: "adddataSource/getOrgList" });
    let datas = {};
    if (appId) {
      datas = await dispatch({
        type: "appListData/queryAppDetail",
        payload: { appId }
      });
    }
    const { ownerDept, ownerDeptName } = datas;
    let ownerMap = [];
    try {
      ownerMap = JSON.parse(datas.owner);
    } catch (e) {
      ownerMap = [];
    }
    const { key, name } = (ownerMap && ownerMap[0]) || {};
    this.setState(
      {
        managerName: appId ? name : userName,
        manager: appId ? key : userId,
        ownerDept: appId ? ownerDept : department,
        ownerDeptName: appId ? ownerDeptName : departmentName
      },
      () => {
        setFieldsValue({ managerName: appId ? name : userName });
      }
    );
    this.setLoading(false);
  };

  managerConfirm = (e, desc) => {
    const {
      form: { setFieldsValue }
    } = this.props;
    const managerName = desc && desc.length > 0 ? desc[0] : "";
    const manager = e && e.length > 0 ? e[0] : "";
    this.setState({
      managerName,
      manager
    });
    setFieldsValue({ managerName });
    this.closeModal();
  };

  closeModal = () => {
    this.setState({ selectVisible: false });
  };

  onDepartmentChange = (e, departmentName) => {
    this.setState({
      ownerDept: !e ? "" : e,
      ownerDeptName:
        departmentName && departmentName.length > 0 ? departmentName[0] : ""
    });
  };

  setLoading = boolean => {
    this.setState({ loadingEdit: boolean });
  };

  handleSubmit = () => {
    this.setLoading(true);
    const {
      dispatch,
      form: { validateFields },
      onCancel,
      appId,
      init = () => {}
    } = this.props;
    validateFields((error, values) => {
      if (error) {
        return;
      }
      const { appName, appDes } = values;
      const { managerName, manager, ownerDept, ownerDeptName } = this.state;
      const owner = JSON.stringify([{ key: manager, name: managerName }]);
      if (appId) {
        dispatch({
          type: "appListData/editApp",
          payload: {
            appId,
            appName,
            appDes,
            owner,
            ownerDept,
            ownerDeptName
          }
        }).then(res => {
          if (res.success) {
            init();
            onCancel();
          } else {
            message.error(`编辑失败${res.errMsg}`);
          }
        });
      } else {
        dispatch({
          type: "appListData/addApp",
          payload: {
            appName,
            appDes,
            owner,
            ownerDept,
            ownerDeptName
          }
        }).then(res => {
          if (res.success) {
            init();
            onCancel();
          } else {
            message.error(`新增失败${res.errMsg}`);
          }
        });
      }
    });
    this.setLoading(false);
  };

  render() {
    const {
      form: { getFieldDecorator },
      orgList: { orgTree = [] } = {},
      userData: {
        userInfo: { userName = "", department = "" }
      },
      appData: { appDetail: { appName, appDes, ownerDept } = {} },
      visible,
      onCancel = () => {},
      appId
    } = this.props;
    const { manager, managerName, selectVisible, loadingEdit } = this.state;
    const formLayout = {
      layout: "horizontal",
      labelCol: { span: 4 },
      wrapperCol: { span: 20 }
    };
    return (
      <Modal
        title={appId ? "编辑应用" : "创建应用"}
        visible={visible}
        onOk={this.handleSubmit}
        onCancel={onCancel}
        destroyOnClose
      >
        <SelectModal
          select={manager}
          selectdesc={managerName}
          visible={selectVisible}
          closeModal={this.closeModal}
          confirm={this.managerConfirm}
          isMutiple={false}
          manager={true}
        />
        <Spin spinning={loadingEdit}>
          <Form {...formLayout}>
            <Form.Item label="应用名称">
              {getFieldDecorator("appName", {
                rules: [
                  { required: true, message: "应用名称不能为空" },
                  { max: 25, message: "应用名称少于25个字" }
                ],
                initialValue: appId ? appName : undefined
              })(<Input style={{ width: 345 }} placeholder="请输入URL" />)}
            </Form.Item>
            <Form.Item label="应用描述">
              {getFieldDecorator("appDes", {
                rules: [{ max: 100, message: "应用描述少于100个字" }],
                initialValue: appId ? appDes : undefined
              })(
                <TextArea
                  style={{
                    width: 345,
                    height: 120
                  }}
                  placeholder="请输入应用描述，可不填"
                  maxLength={100}
                />
              )}
            </Form.Item>
            <Form.Item label="管理员">
              {getFieldDecorator("managerName", {
                rules: [{ required: true, message: "管理员不能为空" }],
                initialValue: appId ? undefined : userName
              })(
                <Input
                  style={{ width: 345 }}
                  placeholder="请选择管理员"
                  onClick={() => {
                    this.setState({ selectVisible: true });
                  }}
                />
              )}
            </Form.Item>
            <Form.Item label="归属部门">
              {getFieldDecorator("ownerDeptName", {
                rules: [{ required: true, message: "归属部门不能为空" }],
                initialValue: appId ? ownerDept : department
              })(
                <TreeSelect
                  treeData={orgTree}
                  onChange={this.onDepartmentChange}
                  placeholder="请选择归属部门"
                  showCheckedStrategy="SHOW_PARENT"
                  style={{ width: 345 }}
                  dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                />
              )}
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    );
  }
}

export default AddApplication;
